var express = require('express'),
    ejs = require('ejs');
    path = require('path'),
    http = require('http'),
    logger = require('morgan'),
    bodyParser = require('body-parser'),
    config = require("./config"),
    mongodb = require('./modules/mongodb');

var app = express();

app.set('port', config.port);
app.set('views', path.join(__dirname, '/views'));

app.engine('.html', ejs.__express);
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, 'public')));

var filter = require("./modules/filter");
var indexRoutes = require('./routes/index'),
    todoRoutes = require('./routes/todo'),
    categoryRoutes = require('./routes/category'),
    tagRoutes = require('./routes/tag'),
    apiRoutes = require('./routes/api');

app.get('/login', filter.test, indexRoutes.login);

app.get('/', filter.test, todoRoutes.index);
app.get('/todo/edit/:id', todoRoutes.edit);
app.post('/todo/edit-submit', todoRoutes.editSubmit);
app.get('/todo/remove/:id', todoRoutes.remove);
app.post('/todo/done-submit/:id', todoRoutes.doneSubmit);
app.post('/todo/star-submit/:id', todoRoutes.starSubmit);

app.get('/category', filter.test, categoryRoutes.index);
app.get('/category/edit/:id', categoryRoutes.edit);
app.post('/category/edit-submit', categoryRoutes.editSubmit);
app.get('/category/remove/:id', categoryRoutes.remove);

app.get('/tag', filter.test, tagRoutes.index);
app.get('/tag/edit/:id', tagRoutes.edit);
app.post('/tag/edit-submit', tagRoutes.editSubmit);
app.get('/tag/remove/:id', tagRoutes.remove);

app.get('/api/get-list/:type', apiRoutes.getList);
app.post('/api/get-list/:type', apiRoutes.getList);

mongodb.connect(function(error){
    if (error) throw error;
});
app.on('close', function(errno) {
    mongodb.disconnect(function(err) { });
});


if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

/*
var server = app.listen(app.get('port'), function() {
    console.log("Express server listening on port " + app.get('port'));
});
*/

module.exports = app;
